<template>
  <div class="app-container">
    <div class="search-container">
      <!-- <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属站点" prop="mixingStationCode">
          <el-select v-model="queryParams.mixingStationCode" placeholder="所属站点" clearable>
            <el-option v-for="item in stationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="waybillCodeFuzzy">
          <el-input v-model="queryParams.waybillCodeFuzzy" placeholder="订单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerNameFuzzy">
          <el-input v-model="queryParams.customerNameFuzzy" placeholder="客户名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringNameFuzzy">
          <el-input v-model="queryParams.engineeringNameFuzzy" placeholder="工程名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="施工部位" prop="buildPlaceFuzzy">
          <el-input v-model="queryParams.buildPlaceFuzzy" placeholder="施工部位" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="waybillStatus">
          <el-select v-model="queryParams.waybillStatus" placeholder="状态" clearable>
             订单状态: 0.新建 1.暂挂 2.启用 3.完成 4.取消
            <el-option v-for="item in statusList" v-bind="item" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常状态" prop="expStatus">
          <el-select v-model="queryParams.expStatus" placeholder="异常状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="异常" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间">
          <el-select v-model="queryParams.timeType">
            <el-option label="预计开盘时间" :value="1" />
            <el-option label="实际开盘时间" :value="2" />
          </el-select>
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" class="ml-8" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form> -->

      <SearchForm
        ref="queryFormRef"
        :model="queryParams"
        :default-collapsed="isCollapsed"
        @search="handleQuery"
        @reset="handleResetQuery"
        @collapsed-change="handleCollapsedChange"
      >
        <el-form-item label="所属站点" prop="mixingStationCode">
          <el-select v-model="queryParams.mixingStationCode" placeholder="所属站点" clearable>
            <el-option v-for="item in stationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="waybillCodeFuzzy">
          <el-input v-model="queryParams.waybillCodeFuzzy" placeholder="订单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerNameFuzzy">
          <el-input v-model="queryParams.customerNameFuzzy" placeholder="客户名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringNameFuzzy">
          <el-input v-model="queryParams.engineeringNameFuzzy" placeholder="工程名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="施工部位" prop="buildPlaceFuzzy">
          <el-input v-model="queryParams.buildPlaceFuzzy" placeholder="施工部位" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="waybillStatus">
          <el-select v-model="queryParams.waybillStatus" placeholder="状态" clearable>
            <!--  订单状态: 0.新建 1.暂挂 2.启用 3.完成 4.取消 -->
            <el-option v-for="item in statusList" v-bind="item" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常状态" prop="expStatus">
          <el-select v-model="queryParams.expStatus" placeholder="异常状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="异常" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间">
          <el-select v-model="queryParams.timeType">
            <el-option label="预计开盘时间" :value="1" />
            <el-option label="实际开盘时间" :value="2" />
          </el-select>
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" class="ml-8" />
        </el-form-item>
      </SearchForm>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <div></div>
          <div>
            <el-button type="primary" @click="handleHeaderEdit">
              <template #icon><ep-Setting /></template>
              编辑表头
            </el-button>
            <el-button @click="handleExport">
              <template #icon><ep-Download /></template>
              导出
            </el-button>
          </div>
        </div>
      </template>
      <el-table v-auto-h="isCollapsed" v-loading="loading" :data="tableData" row-key="id" border highlight-current-row>
        <el-table-column v-for="item in tableColumnsData" :key="item.prop" align="center" :label="item.label" v-bind="item">
          <template v-if="checkTemplate(item.prop)" #default="{ row }">
            <template v-if="item.prop === 'waybillStatus'">
              <span>{{ statusList.find(item => item.value === row.waybillStatus)?.label }}</span>
            </template>
            <template v-else-if="item.prop === 'expStatus'">
              <span v-if="row.expStatus === 1">正常</span>
              <span v-else-if="row.expStatus === 2">异常</span>
            </template>
            <template v-else-if="item.prop === 'expOrderCodeList'">
              <span v-for="(order, index) in row.expOrderCodeList" :key="order">
                <el-link type="primary" @click="handleExpWaybillClick(order)">{{ order }}</el-link>
                <span v-if="index !== row.expOrderCodeList.length - 1">、</span>
              </span>
            </template>
            <template v-else>
              <el-button type="primary" link size="small" @click="handleDetailClick(row.id)">订单详情</el-button>
              <el-button type="primary" class="table-link" link size="small" @click="handleEdit(row)">编辑状态</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-model:page="queryParams.nowPage"
        v-model:pagesize="queryParams.pageSize"
        :total="total"
        @pagination="handlePaginationChange"
      />
    </el-card>
    <Detail :id="detailId" v-model:visible="detailVisible" />
    <WaybillDetail :id="expWaybillId" v-model:visible="expDialogVisible" :waybill-code="expWaybillCode" />
    <!-- 编辑表头 -->
    <el-drawer v-model="drawerVisible" title="编辑表头" size="30%">
      <el-tree :data="headerData" :allow-drop="allowDrop" draggable node-key="prop" />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleHeaderConfirm">确 定</el-button>
          <el-button @click="handleCloseDrawer">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 编辑用户信息 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑状态 "
      width="600"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
        <el-form-item label="订单状态" prop="waybillStatus">
          <el-select v-model="editForm.waybillStatus" placeholder="订单状态">
            <el-option v-for="item in statusList" v-bind="item" :key="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEditCommitClick">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
/**
 * 订单列表
 */
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { AllowDropType } from 'element-plus/es/components/tree/src/tree.type'

import { useRequest } from '@/hooks/useRequest'
import {
  getOrderTableData,
  exportOrderTableData,
  changeOrderStatusRequest,
  getUserTableHeaders,
  setUserTableHeaders
} from '@/api/order/index'
import type { SearchParams, OrderData } from '@/api/order/index'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'
import { getMixingStationList, type MixingStationData } from '@/api/customer/customer'

import Detail from './detail.vue'
import WaybillDetail from '@/views/waybill/detail.vue'

const isCollapsed = ref(true)
const handleCollapsedChange = (collapsed: boolean) => {
  isCollapsed.value = collapsed
}

// 编辑状态
function useEdit(refreshCb) {
  const editDialogVisible = ref(false)
  const editFormRef = ref()
  const editForm = reactive<Pick<OrderData, 'id' | 'waybillStatus'>>({
    id: '',
    waybillStatus: null
  })

  const editFormRules = {
    waybillStatus: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
  }
  const editLoading = ref(false)
  const handleEdit = (row: OrderData) => {
    editForm.id = row.id
    editForm.waybillStatus = row.waybillStatus
    editDialogVisible.value = true
  }

  const handleEditCommitClick = async () => {
    editFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        editLoading.value = true
        changeOrderStatusRequest(editForm)
          .then(() => {
            ElMessage.success('编辑成功')
            editDialogVisible.value = false
            refreshCb()
          })
          .finally(() => {
            editLoading.value = false
          })
      }
    })
  }
  return {
    editDialogVisible,
    editFormRef,
    editForm,
    editFormRules,
    editLoading,
    handleEdit,
    handleEditCommitClick
  }
}

// 订单状态: 0.新建 1.暂挂 2.启用 3.完成 4.取消
const statusList: OptionType[] = [
  { label: '新建', value: 0 },
  { label: '暂挂', value: 1 },
  { label: '启用', value: 2 },
  { label: '完成', value: 3 },
  { label: '取消', value: 4 }
]

const queryFormRef = ref(ElForm)

const queryParams = reactive<Partial<SearchParams>>({ waybillStatus: 2, timeType: 1, nowPage: 1, pageSize: 10 })

const tableColumnsData = shallowRef([])

const checkTemplate = (prop: string) => {
  return ['operate', 'waybillStatus', 'expStatus', 'expOrderCodeList'].includes(prop)
}

const route = useRoute()
const routeName = route.name as string
const { data: stationRes } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queryParams.mixingStationCode = defaultMixingStation.number
    }
  },
  onAfter() {
    handleQuery()
  }
})
const stationOptions = computed(() => stationRes.value?.result || [])

getHeadersData()

async function getHeadersData() {
  const { result } = await getUserTableHeaders({ routeName })
  if (result.headerCtx) {
    const data = JSON.parse(result.headerCtx)
    tableColumnsData.value = data
  }
}

const total = ref(0)
const tableData = ref([])
const { run, loading } = useRequest(getOrderTableData, {
  manual: true,
  defaultParams: [queryParams],
  onSuccess({ result }) {
    const { records, total: totalRes } = result
    total.value = totalRes
    tableData.value = records.map(row => {
      if (typeof row.expOrderCodeList === 'string') {
        row.expOrderCodeList = row.expOrderCodeList.split(',')
      }
      return row
    })
  }
})

const handleQuery = () => {
  run(queryParams)
}

const { editDialogVisible, editFormRef, editForm, editFormRules, editLoading, handleEdit, handleEditCommitClick } = useEdit(handleQuery)

const drawerVisible = ref(false)
const headerData = shallowRef([])
// 不允许插入
const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  return type !== 'inner'
}
const handleHeaderEdit = () => {
  headerData.value = [...tableColumnsData.value]
  drawerVisible.value = true
}
const handleCloseDrawer = () => {
  drawerVisible.value = false
}
const handleHeaderConfirm = () => {
  setUserTableHeaders({
    routeName,
    headerCtx: JSON.stringify(headerData.value)
  }).catch(() => {
    // 失败需要重新刷新
    getHeadersData()
  })
  tableColumnsData.value = [...headerData.value]
  handleCloseDrawer()
}

const handleExport = () => {
  exportOrderTableData(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.timeType = 1
  queryParams.startTime = ''
  queryParams.endTime = ''
  handleQuery()
}

const handlePaginationChange = (page: number, pageSize: number) => {
  queryParams.nowPage = page
  queryParams.pageSize = pageSize
  handleQuery()
}

const detailVisible = ref(false)
const detailId = ref('')
const handleDetailClick = (id: OrderData['id']) => {
  detailId.value = id
  detailVisible.value = true
}

const expDialogVisible = ref(false)
const expWaybillId = ref('')
const expWaybillCode = ref('')
const handleExpWaybillClick = (code: string) => {
  expWaybillId.value = ''
  expWaybillCode.value = code
  expDialogVisible.value = true
}
</script>
<style lang="scss" scoped>
.table-link {
  margin-left: 0;
}
</style>
